﻿#include "DataBaseConnector.h"

#include <qdebug.h>
#include <qsqlquery.h>
#include <qsqlerror.h>

#include "MacroDefinition.h"

DataBaseConnector::DataBaseConnector()
{
  setObjectName(getClassNameFirstLow<DataBaseConnector>());
}

DataBaseConnector::~DataBaseConnector()
{
  QSqlDatabase::database(DATABASE_NAME).close();
}

bool DataBaseConnector::connectToDataBase()
{
  QSqlDatabase database=QSqlDatabase::addDatabase(DATABASE_DRIVER,DATABASE_NAME);
  database.setHostName(DATABASE_HOSTNAME);
  database.setPort(DATABASE_PORT);
  database.setDatabaseName(DATABASE_NAME);
  database.setUserName(DATABASE_USERNAME);
  database.setPassword(DATABASE_PASSWORD);
  if(database.open())
    {
      logSaver->saveLog("open database successful");
      logSaver->saveLog("database name :"+database.databaseName());
      logSaver->saveLog("database driver :"+database.driverName());
      logSaver->saveLog("database hostname :"+database.hostName());
      logSaver->saveLog("database port :"+QString::number(database.port()));
      logSaver->saveLog("database username :"+database.userName());
      logSaver->saveLog("database password :"+database.password());
      return true;
    }
  else
    {
      logSaver->saveLog("open database failed",LogSaver::Critical);
      return false;
    }
}

QSqlQuery DataBaseConnector::exec(QString mysql)
{
  return QSqlDatabase::database(DATABASE_NAME).exec(mysql);
}
